import MesHelp from '../Http/MesHelp'

// 聊天相关类型定义
export interface ChatRequest {
  message: string
  sessionId: string
  userId?: string
}

export interface ChatResponse {
  message: string
  sessionId: string
  timestamp: string
  isAI: boolean
  userId?: string
}

export interface ChatSession {
  sessionId: string
  createdAt: string
  isActive: boolean
}

// 聊天API服务
export class ChatService {
  private static baseUrl = '/api/chat'

  /**
   * 发送消息到智能客服
   */
  static async sendMessage(request: ChatRequest): Promise<ChatResponse> {
    try {
      const response = await MesHelp.post(`${this.baseUrl}/send`, request)
      // 处理ApiResult格式的响应
      if (response.data && response.data.code === 200) {
        return response.data.data
      } else {
        throw new Error(response.data?.message || '发送消息失败')
      }
    } catch (error) {
      console.error('发送消息失败:', error)
      throw error
    }
  }

  /**
   * 获取聊天历史
   */
  static async getChatHistory(sessionId: string): Promise<ChatResponse[]> {
    try {
      const response = await MesHelp.get(`${this.baseUrl}/history/${sessionId}`)
      // 处理ApiResult格式的响应
      if (response.data && response.data.code === 200) {
        return response.data.data
      } else {
        throw new Error(response.data?.message || '获取聊天历史失败')
      }
    } catch (error) {
      console.error('获取聊天历史失败:', error)
      throw error
    }
  }

  /**
   * 创建新的聊天会话
   */
  static async createSession(): Promise<ChatSession> {
    try {
      const response = await MesHelp.post(`${this.baseUrl}/session`)
      // 处理ApiResult格式的响应
      if (response.data && response.data.code === 200) {
        return response.data.data
      } else {
        throw new Error(response.data?.message || '创建会话失败')
      }
    } catch (error) {
      console.error('创建会话失败:', error)
      throw error
    }
  }
}

export default ChatService
